<template>
  <view class="login" :style="pageHeight">
    <image :src="vuex_imgPath+'/login_bg.png'" class="login-bg" />
    <view class="login-int">
      <view class="t-int">账号</view>
      <view class="login-int-box account-box">
        <view class="phone-box">
          <uni-easyinput
            v-model="loginAccount"
            placeholder="用户名/手机号码"
            font-size="28rpx"
            :input-border="false"
            :trim="true"
            clear-size="18"
            clearable
            placeholder-style="color: #999"
          />
        </view>
      </view>
    </view>
    <view class="login-int">
      <view class="t-int">密码</view>
      <view class="login-int-box">
        <view class="password-box">
          <uni-easyinput
            v-model="password"
            :type="!isShowPassword ? 'password' : 'text'"
            clearable
            :input-border="false"
            :password-icon="false"
            :trim="true"
            clear-size="18"
            placeholder="登录密码"
            font-size="28rpx"
            placeholder-style="color: #999"
          />
        </view>
        <image
          class="password-change"
          :src="!isShowPassword ? openEyeIcon : closeEyeIcon"
          @click="changeInputTypeFn"
        />
      </view>
    </view>
    <view class="login-btn">
      <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="Login">立即登录</button>
    </view>
    <view
      class="forget-password"
      @click="forgetPasswordFn"
    >
      忘记密码?
    </view>
    <!-- #ifdef H5 -->
    <view>
      <view>
        <!--组件-->
        <slideVerify v-if="slideShowStatus" @seccess="slideYzSeccess" />
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import { loginServiceV3, traceless } from '@/api/login.js';
import { passwordTestFn } from '@/login/loginCommonFn'
import { Base64 } from '@/lib/Base64';
import '@/static/scss/login.scss';
import { getAuthCode } from '@/utils/login';
import { getLoginInfoFn, initSlide, deepLinkkUrl, tdkUrl } from '@/common/common'
import slideVerify from '@/components/slide-verify.vue';

export default {
  name: 'PasswordLogin',
  components: {
    slideVerify
  },

  data() {
    return {
      pageHeight: '',
      loginAccount: '',
      password: '',
      isShowPassword: false, // 是否展示密码
      closeEyeIcon: '/static/shopIcon/close_eye.png', //闭眼icon地址
      openEyeIcon: '/static/shopIcon/open_eye.png', //睁眼icon地址
      type: '',
      typePage: '',
      callbackUrl: '',
      urlParams: '',
      registParams: '',
      slideShowStatus: false,
      clicktime: true,
      skuId:'',
      title:'',
      exchangeType:'',
    }
  },
  onLoad(option) {
    if (this.vuex_loginStatus) {
      this.setBackUrlFn()
      uni.redirectTo({
        url: this.callbackUrl
      })
    }
    const { type = '', callbackUrl = '', urlParams = '', typePage = '', typeDetail = '', productDetailSkucode = '',shareMemberId='' } = option
    this.type = type
    this.typePage = typePage
    this.callbackUrl = callbackUrl
    this.typeDetail = typeDetail
    this.productDetailSkucode = productDetailSkucode
    this.shareMemberId =shareMemberId
    this.urlParams = urlParams == '' ? {} : JSON.parse(urlParams)
    if(this.type == 'pointsGoodsDetail'){
    this.skuId =this.urlParams.skuId
    this.title =this.urlParams.title
    this.exchangeType =this.urlParams.exchangeType
    }
    console.log('商品详情分享',this.urlParams,shareMemberId)
    //#ifdef H5
    //initSlide()
    // #endif
  },
  methods: {
    setBackUrlFn() {
      /*根据账号类型跳转对应首页*/
      if (!this.callbackUrl && (!this.vuex_loginStatus || (this.vuex_loginStatus && this.vuex_memberInfo && (this.vuex_memberInfo.accountType == 20 || this.vuex_memberInfo.accountType == 30)))) {
        this.callbackUrl = '/shopIndex/shopIndex'
      } else {
        !this.callbackUrl ? this.callbackUrl = '/pages/index/index' : ''
      }
    },
    /*修改密码输入框类型*/
    changeInputTypeFn() {
      this.isShowPassword = !this.isShowPassword
    },
    /*忘记密码*/
    forgetPasswordFn() {
      uni.navigateTo({
        url: `/login/resetPassword/index`
      })
    },
    /*登录
    * 账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
    * */
    Login() {
      const _this = this
      if (!this.loginAccount) {
        this.$u.toast('请输入用户名/手机号')
        return
      }
      if (!passwordTestFn(this.password)) {
        return
      }
      // #ifdef H5
      // window.nvc.getNVCValAsync(function(nvcVal) {
      //   console.log('点击获取验证码掉无痕')
      //   if (_this.slideShowStatus == true) {
      //     _this.slideShowStatus = false
      //   }
      //   _this.tranClassFn(decodeURIComponent(nvcVal))
      // });
      this.loginServiceV3Fn()
      // #endif
      // #ifdef MP-ALIPAY || MP-WEIXIN
      this.loginServiceV3Fn()
      // #endif
    },
    loginServiceV3Fn() {
      const provider = this.vuex_provider;
      getAuthCode(provider, (loginRes) => {
        if (loginRes.code) {
          this.$u.vuex('vuex_login_code', loginRes.code)
        }
      })
      const params = {
        loginAccount: this.loginAccount,
        password: Base64.encode(this.password),
        account_type: 20,
        distinctId: '', //公共参数：神策匿名 id
        device_platform: this.vuex_provider, //公共参数(神策)：设备来源:android,ios,pc,h5,dingding
        platform: this.vuex_provider, //登陆平台
        version_code: '145', //公共参数：版本号
        registerPlatform: 84
      }
      if (this.vuex_mapAddress) {
        // 小程序新增登录/注册所在地信息
        const { provinceName, cityName, districtName } = this.vuex_mapAddress
        params.commonParamProvinceName = provinceName
        params.commonParamCityName = cityName
        params.commonParamDistrictName = districtName
      }
      loginServiceV3(params).then((res) => {
        if (Number(res.code) == 0) {
          /**
         * 账号状态 10：正常； 20：关闭； 30：注销
          */
          if (res.memberInfo.status == 20 || res.memberInfo.status == 30 || (res.memberInfo.accountType == 30 && !res.crmCustomerInfos)) {
            uni.$u.toast('该账号无权登录，有问题请联系客服！');
            return;
          }
          // #ifdef H5
          if (res.memberInfo.accountType == 10) { //登录账号是数采账号
            window.location.href = deepLinkkUrl.develop + '/h5/fsyuncai/linkApp.html?isQianyue=1&isM=1'
            return
          }

          // #endif
          const {
            memberInfo,
            token,
            crmCustomerInfos,
            memberCompanyInfo,
            memberLevelResp,
          } = res
          this.$u.vuex('vuex_accountInfo', {
            loginAccount: memberInfo.loginAccount,
            mobilePhone: memberInfo.mobilePhone,
            memberId: memberInfo.memberId,
          })
          getLoginInfoFn(memberInfo.memberId)
          this.$u.vuex('vuex_token', token)
          this.$u.vuex('vuex_memberInfo', memberInfo)
          this.$u.vuex('vuex_memberCompanyInfo', memberCompanyInfo)
          this.$u.vuex('vuex_crmCustomerInfos', crmCustomerInfos)
          this.$u.vuex('vuex_memberLevelResp', memberLevelResp)
          this.$u.vuex('vuex_loginStatus', true)
          // #ifdef H5
          this.$cookie.set('memberId', memberInfo.memberId, 365)
          this.$cookie.set('loginAccount', memberInfo.loginAccount, 365)
          this.$cookie.set('accountType', memberInfo.accountType, 365)
          this.$cookie.set('platformName', memberInfo.platformType, 365)
          this.$cookie.set('sourceUrl', encodeURIComponent(window.location.href), 1)
          this.$cookie.set('lgdomain', this.$cookie.getUrlDomain(), 365);
          this.$cookie.set('registerSource', memberInfo.registerSource, 365);
          const mySelectStation = JSON.parse(localStorage.getItem('my_select_station'));
          uni.$u.vuex('vuex_cityInfo', mySelectStation);
          // #endif
          let paramStr = ''
          if (this.urlParams) {
            for (const urlParamsKey in this.urlParams) {
              paramStr += urlParamsKey + '=' + this.urlParams[urlParamsKey] + '&'
            }
          }
          this.setBackUrlFn()
          if (this.type == 'order') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'my') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'ground') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.typePage == 'h5') {
            uni.reLaunch({ url: '/myAccount/giftCard/index' })
          } else if(this.type == 'pointsGoodsDetail'){
          uni.reLaunch({ url: '/myAccount/pointsMall/pointsGoodsDetail?skuId='+this.skuId+'&title=' + this.title + '&exchangeType=' +this.exchangeType})
        
          }else {
            // #ifdef MP-ALIPAY || MP-WEIXIN
            console.log('商品详情账号密码登录',paramStr)
            uni.reLaunch({ url: this.callbackUrl + '?' + paramStr })
            // #endif
            // #ifdef H5
            if (this.typeDetail == 'detail' && this.productDetailSkucode != '') {
              window.location.href = `${tdkUrl.develop}/productsku/${this.productDetailSkucode}.html?page=1&shareMemberId=${this.shareMemberId}`
            }
            // #endif
          }
        } else if (res.code == 2003) { //登录账号是 分销
          this.$u.toast('您的手机号码已注册工品云采平台，请前往www.xfsbuy.com登录！')
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    tranClassFn(parame) {
      traceless({ nvcVal: parame }).then((res) => {
        this.resultTrace(res);
      }).catch(() => {
        // eslint-disable-next-line no-mixed-spaces-and-tabs
      })
    },
    resultTrace(res) {
      if (res.data == 200 || res.data == 100) {
        //验证通过
        this.loginServiceV3Fn()
        return;
      }

      if (res.data == 400) {
        //验证不通过
        var ncoption = {
          // 声明滑动验证需要渲染的目标ID。
          renderTo: 'nc',
        }
        // 唤醒二次验证（滑动验证码）
        window.nvc.getNC(ncoption);
        this.slideShowStatus = true
        return;
      }

      if (res.data == 900) {
        //二次验证验证不通过
        console.log('验证失败', 3000);
        return;
      }

      if (res.data == 800) {
        //直接拦截
        console.log('您的账号存在异常，请联系在线客服！', 3000);
        return;
      }
    },
    //接无痕验证收验证成功的值
    slideYzSeccess(data) {
      console.log('400时出现的滑块 当移动滑块成功之后返回')
      //会话ID（sessionId）、签名串（sig）、请求唯一标识（token）
      console.log(data.sessionId)
      console.log(data.sig)
      console.log(data.token)
      this.loginServiceV3Fn()
    },
  }
}
</script>

<style scoped lang="scss">
.login{
  padding-top: 50rpx;
  .forget-password {
    width: 128rpx;
    height: 34rpx;
    line-height: 34rpx;
    color: $uni-orange;
    margin-top: 24rpx;
    font-size: $uni-font-size-base;
  }
}
.login-int-box{
  border: 2rpx solid $uni-grey-e2!important;
  .phone-box {
    /deep/ .uni-easyinput {
      padding: 0 !important;
      .uni-easyinput__content{
        /*#ifdef MP-ALIPAY*/
        width: 564rpx;
        /*#endif*/
        /*#ifdef MP-WEIXIN*/
        width: 580rpx;
        /*#endif*/
      }
      /deep/ .uniui-clear{
        color: #c0c4cc;
      }
    }
  }
  .password-box {
    /deep/ .uni-easyinput {
      padding: 0 !important;
      .uni-easyinput__content{
        /*#ifdef MP-ALIPAY*/
        width: 514rpx;
        /*#endif*/
        /*#ifdef MP-WEIXIN*/
        width: 524rpx;
        /*#endif*/
      }
      /deep/ .uniui-clear{
        color: #c0c4cc;
      }
    }
  }
  /deep/ input {
    height:72rpx;
    padding: 0 32rpx;
  }
  .password-box {
    width:584rpx;
  }
  .password-change{
    position: absolute;
    width: 32rpx;
    height: 32rpx;
    top: 20rpx;
    right: 24rpx;
    /* #ifdef H5 */
     right: 56rpx;
    /*#endif*/
  }
}
/deep/.account-box  .uniui-clear{
  position: absolute;
  right: 20rpx;
  top: 18rpx;
}

</style>
